<?php

namespace App\Supports\WithdrawFreelance\GaoDeng;

use Exception;
use App\Models\User;
use App\Models\BankCard;
use App\Models\Freelance;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException;
use GuzzleHttp\Client;

class GaoDeng
{
	protected $request_url = 'https://api-js-ets.wetax.com.cn';

	public function __construct(User $user)
	{
		if (app()->environment('production')) {
			$request_url = 'https://api-js.wetax.com.cn';
		}

		$this->config = config('gaodeng');
		$this->appkey = $this->config['appkey'];
		$this->appsecret = $this->config['appsecret'];
		$this->aesIV = $this->config['aesIV'];
		
		$this->localUser = $user;

		if (!$this->localUser->isPhoneBound()) {
			abort(400, '会员账号手机号码未绑定');
		}
	}

    //SHA256
	function encrypt_sha256($str = ''){
	    return hash_hmac("sha256", $str ,$this->appsecret);
	}
	
	protected function getGuzzleClient()
	{
		return new Client(['Content-Type' => 'application/json']);
	}
	
	public function register()
	{
		try {

			$freelance = $this->localUser->freelance;
			if(!$freelance){

				$freelance = request();
			}
			$method = '/api/balance/identityauditresult';

			$params = [
				'name' => $freelance->real_name,
				'certificate_num' => $freelance->id_no,
				'merchant_id' => $this->appkey,
			];

			$response = $this->commonFieldHandle($params, $method, '');

			Log::debug(json_encode($response));

			if($response['code'] == '1002'){


				$gd_encrypt_params = [
					'name' => $freelance->real_name,
					'idNumber' => $freelance->id_no,
					'phoneNumber' => $this->localUser->phone,
					'merchantId' => $this->appkey,
				];

				$gd_encrypt = openssl_encrypt(json_encode($gd_encrypt_params),'AES-256-CBC',$this->appsecret,0,$this->aesIV);
				$gd_url = "https://toolh5-ets.wetax.com.cn/?data=".$gd_encrypt.'&appkey='.base64_encode($this->appkey); 

				if(!$this->localUser->freelance){
					Freelance::create([
						'real_name' => $freelance->real_name,
						'id_no' => $freelance->id_no,
						'id_card_front' => $freelance->id_card_front,
						'id_card_back' =>  $freelance->id_card_back,
						'is_auth' => false,
						'pers_no' => '',
						'user_id' => $this->localUser->id,
						'gd_url' => $gd_url,
					]);

				}else{
					$this->localUser->freelance->update([
						'gd_url' => $gd_url,
					]);
				}
				
			}elseif($response['code'] == '0'){
				if(!$this->localUser->freelance){
					Freelance::create([
						'real_name' => $freelance->real_name,
						'id_no' => $freelance->id_no,
						'id_card_front' => $freelance->id_card_front,
						'id_card_back' =>  $freelance->id_card_back,
						'is_auth' => true,
						'pers_no' => '',
						'user_id' => $this->localUser->id,
						'gd_encrypt' => '',
					]);

				}else{
					$this->localUser->freelance->update([
						'is_auth' => true,
					]);
				}

			}else{

				abort(400, "提现账户创建失败:{$response['msg']}");
			}
		} catch (Exception $exception) {
			abort(400, $exception->getMessage());
		}

		return $this->localUser;
	}

	public function getCardNo($withdraw_method,$banalnces){

		$recvCardNo = '';
		if($withdraw_method == 'wxpay'){
			$recvCardNo = $this->localUser->wx_openid;
			$banalnces[0]['payment_way'] = 9;
			$banalnces[0]['wx_openId'] = $this->localUser->wx_openid;
		}elseif($withdraw_method=='alipay'){
			$recvCardNo = $this->localUser->alipay_user_no;
			$banalnces[0]['payment_way'] = 3;
			$banalnces[0]['payment_account'] =$this->localUser->alipay_user_no;
		}else{
			$recvCardNo =  !empty($this->localUser->bankCards->find(request()->bank_card_id)) 
							? $this->localUser->bankCards->find(request()->bank_card_id)->cert_number : '';
			$bankName = !empty($this->localUser->bankCards->find(request()->bank_card_id)) 
						? $this->localUser->bankCards->find(request()->bank_card_id)->card_name : '';

			$banalnces[0]['payment_way'] = 1;
			$banalnces[0]['bank_name'] =$bankName;
			$banalnces[0]['bankcard_num'] =$recvCardNo;

			if(empty($bankName)){

				abort(400, "收款方不能为空");
			}
		}
		if(empty($recvCardNo)){

			abort(400, "提现账户不能为空");
		}
		return $banalnces;

	}

	public function getBankName($withdraw_method){
		$bankName = '';
		if($withdraw_method == 'wxpay'){
			$bankName = '微信钱包';
		}elseif($withdraw_method == 'alipay'){
			$bankName = '支付宝';
		}else{
			$bankName = !empty($this->localUser->bankCards->find(request()->bank_card_id)) 
						? $this->localUser->bankCards->find(request()->bank_card_id)->card_name : '';
		}
		if(empty($bankName)){

			abort(400, "收款方不能为空");
		}
		return $bankName;

	}

	public function getRand(){
		$rand = time().rand('10000','99999');
		return $rand;
	}

	public function withdraw()
	{
		try {
			$scene_method = "/api/common/getbusinessscene";

			$scene_params = [
				'merchant_id' => $this->appkey,
			];

			$scene_response = $this->commonFieldHandle($scene_params, $scene_method, '');

			if($scene_response['code'] != '0'){
				abort(400, "提现失败:{$scene_response['msg']}");
			}
			$business_scenario_code = $scene_response['data'][0]['business_scenario_code'];
			

			$compliance_method = "/api/Common/GetComplianceField";

			$compliance_params = [
				'merchant_id' => $this->appkey,
				'business_scene_code' => $business_scenario_code,
			];

			$compliance_response = $this->commonFieldHandle($compliance_params, $compliance_method, '');

			if($compliance_response['code'] != '0'){
				abort(400, "提现失败:{$compliance_response['msg']}");
			}
			
			$withdraw_method = request()->withdraw_method;

			$method = "/api/balance/CreateForBatch";
			$balances[0] = [
				'order_random_code' => $this->getRand(),
				'name' => $this->localUser->freelance->real_name,
				'certificate_type' => 1,
				'certificate_num' => $this->localUser->freelance->id_no,
				'phone_num' => $this->localUser->phone,
				'settle_amount' => request()->withdraw_amount,
			];
			$balances = $this->getCardNo($withdraw_method,$balances);
			
			$params = [
				'business_scene_code' => $business_scenario_code,
				'balances' => $balances,
				'data_type' => 0,
				'version' => 'V1',
				"task_name" => "省钱小卖部推广任务",
				"task_scope" => '一天',
				"sales_product" => "母婴产品",
				"sales_mode" => "省钱小卖部推广",
				"sales_sum" => "1个",
				"settle_rule" => "推广数量*产品数量",
				"file_url" => "https://littleshop.oss-cn-beijing.aliyuncs.com/uploads/images/202109/22/00b9d8c3bf33c14c31676cbc994f7806.jpg"
			];


			$response = $this->commonFieldHandle($params,$method,$_SERVER['HTTP_HOST']."/api/v1/withdraws/freelances/notify");
			
			
			Log::debug(json_encode($response));
			
			if ($response['code'] == '0') {
				$withdraw = $this->localUser->withdraws()->create([
					'charge_type' => 'gaodeng',
					'method' => request('withdraw_method'),
					'channel' => '高灯灵活用工',
					'plat_batch_no' => $balances[0]['order_random_code'],
					'status' => 'pending',
				]);
				
			} else {
				abort(400, "提现失败:{$response['msg']}");
			}
		} catch (Exception $exception) {
			abort(400, $exception->getMessage());
		}
		
		return $this->localUser;
	}

	public function refund($orderCodes){

		$method = "/api/balance/refundbalance";

		$params = [
			'merchant_id' => $this->appkey,
			'order_random_code' => [$orderCodes],
		];

		$response = $this->commonFieldHandle($params, $method, '');

		if($response['code'] != '0'){
			abort(400, "退款失败:{$scene_response['msg']}");
		}

	}


	public function commonFieldHandle($params,$method,$callback){

			$timestamp = time();
			$paramBody["data"] = openssl_encrypt(json_encode($params),'AES-256-CBC',$this->appsecret,0,$this->aesIV);

			$paramHeader["Content-Type"] =  'application/json';
			$paramHeader["request_id"] = $this->getRand();
			$paramHeader["appkey"] = $this->appkey;
			$paramHeader["timestamp"] = $timestamp;
			$paramHeader["sign_type"] = 'sha256';
			$paramHeader["signature"] = $this->encrypt_sha256($this->appkey.$timestamp.$this->appsecret);
			//$paramHeader["signature"] = $this->encrypt_sha256('testappkey1562912285testappsecret');
			$paramHeader["callback_url"] = !empty($callback) ? base64_encode($callback) : '';
			$paramHeader["version"] = "2.0";

			

			$result = $this->curl_request($this->request_url.$method,json_encode($paramBody),120,null,null,$paramHeader);
			
			$response = json_decode($result, true);

			return $response;


	}


	public static function curl_request($url,$post, $timeout=120, $json=false, $Multipart =false,$headers=null){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);

        #curl_setopt($curl, CURLOPT_USERAGENT, 'YOP_PHP_Client_API');
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);


        if($headers!=null) {
            $headerArray=array();
            foreach ($headers as  $key => $value) {
                array_push($headerArray,$key.":".$value);
            }
            curl_setopt($curl, CURLOPT_HTTPHEADER,  $headerArray);
        }

        if($post) {
            curl_setopt($curl, CURLOPT_POST, 1);
            //curl_setopt($curl, CURLOPT_POSTFIELDS, is_array($post)?http_build_query($post):$post);
            curl_setopt($curl, CURLOPT_POSTFIELDS, is_array($post)?http_build_query($post,null,'&'):$post);

        }



        if($Multipart){
            curl_setopt ($curl, CURLOPT_SAFE_UPLOAD, false);
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
        }
        $TLS = substr($url, 0, 8) == "https://" ? true : false;
        if($TLS) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
        }

        curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);

        $data = curl_exec($curl);

        if (curl_errno($curl)) {
            return curl_error($curl);
        }
        curl_close($curl);


        if ($json){
            return json_decode($data,true);
        }
        return $data;

    }
 
   
}
